package com.jiaoyou.baojian.agora;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.Gson;
import com.jiaoyou.baojian.BaojianApplication;
import com.jiaoyou.baojian.MainActivity;
import com.jiaoyou.baojian.activity.CallinActivity;
import com.jiaoyou.baojian.activity.SplashActivity;
import com.jiaoyou.baojian.constvalue.ConstValue;
import com.jiaoyou.baojian.otto.AppBus;
import com.jiaoyou.baojian.otto.Event;
import com.jiaoyou.baojian.utils.Utils;

import java.util.Timer;
import java.util.TimerTask;

import io.agora.AgoraAPI;
import io.agora.AgoraAPIOnlySignal;
import io.agora.IAgoraAPI;

import static io.agora.IAgoraAPI.ECODE_LOGIN_E_ALREADY_LOGIN;

/**
 * Created by DemonZYM on 17/9/19.
 */

public class AgoraHelper {
    private Context context;
    public AgoraAPIOnlySignal agoraAPI;
    public boolean isLogin = false;
    public boolean isInited = false;
    private AgoraHelper(Context c){
        context = c;
    }

    private static volatile AgoraHelper agoraHelper;
    public static AgoraHelper getInstance(){
        synchronized (AgoraHelper.class){
            if(agoraHelper == null)
                agoraHelper = new AgoraHelper(BaojianApplication.getInstance());
        }
        return agoraHelper;
    }

    public void init() {
        isInited = true;
        agoraAPI = AgoraAPIOnlySignal.getInstance(context, ConstValue.AGORA_APPID);
        agoraAPI.callbackSet(iCallBack);
    }

    public void setBackground(){
        Log.e("agora_timer", "setBackground");
        agoraAPI.setBackground(1);
        agoraAPI.ping();
    }

    public void setForground(){
        Log.e("agora_timer", "setForground");
        agoraAPI.setBackground(0);
    }

    public void setupSplashActivity(SplashActivity splashActivity){
        context = splashActivity;
    }

    public void setupMainActivity(MainActivity mainActivity){
        context = mainActivity;
    }

    private IAgoraAPI.ICallBack iCallBack = new IAgoraAPI.ICallBack() {
        @Override
        public void onReconnecting(int i) {
            Log.e("iCallBack", "onReconnecting");
        }

        @Override
        public void onReconnected(int i) {
            Log.e("iCallBack", "onReconnected");
        }

        @Override
        public void onLoginSuccess(int i, int i1) {
            isLogin = true;
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_LOGIN_SUCCESS);
                }
            });
        }

        @Override
        public void onLogout(int i) {
            isLogin = false;
            Log.e("iCallBack", "onLogout");
        }

        @Override
        public void onLoginFailed(final int i) {
            isLogin = false;
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_LOGIN_ERROR);
                }
            });
        }

        @Override
        public void onChannelJoined(final String channelID) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(new Event(Event.AGORA_CHANNEL_JOIN_SUCCESS, channelID));
                }
            });
        }

        @Override
        public void onChannelJoinFailed(final String channelID, int ecode) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(new Event(Event.AGORA_CHANNEL_JOIN_FAILED, channelID));
                }
            });
        }

        @Override
        public void onChannelLeaved(String s, int i) {
            Log.e("iCallBack", "onChannelLeaved");
        }

        @Override
        public void onChannelUserJoined(String account, int uid) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_CHANNEL_USER_JOINED);
                }
            });
        }

        @Override
        public void onChannelUserLeaved(String account, int uid) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_CHANNEL_USER_LEAVED);
                }
            });
        }

        @Override
        public void onChannelUserList(String[] strings, int[] ints) {

        }

        @Override
        public void onChannelQueryUserNumResult(String s, int i, int i1) {

        }

        @Override
        public void onChannelAttrUpdated(final String channelID, final String name, final String value, final String type) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    //频道属性变化
                    AppBus.getInstance().post(
                            new Event(Event.AGORA_CHANNEL_ATTR_CHANGED,
                                    new Gson().toJson(
                                            new ChannelAttr(channelID, name, value, type))));
                }
            });
        }

        @Override
        public void onInviteReceived(final String channelID, final String account, int uid, final String extra) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    //接到呼叫
                    AppBus.getInstance().post(Event.AGORA_INVITE_RECEIVED);
                    Intent intent1 = new Intent(BaojianApplication.getInstance(), CallinActivity.class);
                    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent1.putExtra("extra", extra);
                    intent1.putExtra("channelId", channelID);
                    intent1.putExtra("account", account);
                    BaojianApplication.getInstance().startActivity(intent1);
                }
            });
        }

        @Override
        public void onInviteReceivedByPeer(String channelID, String account, int uid) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    //对方接到了呼叫
                    AppBus.getInstance().post(Event.AGORA_INVITE_RECEIVED_BY_PEER);
                }
            });
        }

        @Override
        public void onInviteAcceptedByPeer(String channelID, String account, int uid, String extra) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_INVITE_ACCEPTED_BY_PEER);
                }
            });
        }

        @Override
        public void onInviteRefusedByPeer(String s, String s1, int i, String s2) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_INVITE_REFUSED_BY_PEER);
                }
            });
        }

        @Override
        public void onInviteFailed(String channelID, String account, int uid, final int ecode, String s2) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    switch (ecode) {
                        case AgoraAPI.ECODE_INVITE_E_OTHER:
//                            AppBus.getInstance().post(Event.AGORA_INVITE_E_OTHER);
                            //other error 一般是指没有被叫方的id，具体就是声优是老版本的，没有注册voip的id，所以实际上就是流失的那批声优，所以这里直接认为对方不在线
//                            AppBus.getInstance().post(Event.AGORA_INVITE_E_PEER_OFFLINE);
//                            break;
                        case AgoraAPI.ECODE_INVITE_E_PEEROFFLINE:
                        case AgoraAPI.ECODE_GENERAL_E_NOT_LOGIN:
                            AppBus.getInstance().post(Event.AGORA_INVITE_E_PEER_OFFLINE);
                            break;
                        case AgoraAPI.ECODE_INVITE_E_NET:
                            AppBus.getInstance().post(Event.AGORA_INVITE_E_NET);
                            break;
                        case AgoraAPI.ECODE_INVITE_E_REINVITE:
                            AppBus.getInstance().post(Event.AGORA_INVITE_E_REINVITE);
                            break;
                        case AgoraAPI.ECODE_INVITE_E_TIMEOUT:
                            AppBus.getInstance().post(Event.AGORA_INVITE_E_TIMEOUT);
                            break;
                    }
                }
            });
        }

        @Override
        public void onInviteEndByPeer(String s, String s1, int i, String s2) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_INVITE_END_BY_PEER);
                }
            });
        }

        @Override
        public void onInviteEndByMyself(String s, String s1, int i) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(Event.AGORA_INVITE_END_BY_MYSELF);
                }
            });
        }

        @Override
        public void onInviteMsg(String s, String s1, int i, String s2, String s3, String s4) {
            Log.e("iCallBack", "onInviteMsg");
        }

        @Override
        public void onMessageSendError(String s, int i) {
            Log.e("iCallBack", "onMessageSendError");
        }

        @Override
        public void onMessageSendProgress(String s, String s1, String s2, String s3) {
            Log.e("iCallBack", "onMessageSendProgress");
        }

        @Override
        public void onMessageSendSuccess(String s) {
            Log.e("iCallBack", "onMessageSendSuccess");
        }

        @Override
        public void onMessageAppReceived(String s) {
            Log.e("iCallBack", "onMessageAppReceived");
        }

        @Override
        public void onMessageInstantReceive(String account,int uid,String msg) {
            Log.e("iCallBack", "onMessageInstantReceive");
        }

        @Override
        public void onMessageChannelReceive(final String channelID, String account, int uid, final String msg) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
                    AppBus.getInstance().post(
                            new Event(Event.AGORA_MSG_CHANNEL_RECEIVE,
                                    new Gson().toJson(
                                            new ChannelMsg(channelID, msg))));
                }
            });
        }

        @Override
        public void onLog(String s) {
            Log.e("iCallBack", "onLog:" + s);
        }

        @Override
        public void onInvokeRet(String s, int i, String s1, String s2) {
            Log.e("iCallBack", "onInvokeRet");
        }

        @Override
        public void onMsg(String s, String s1, String s2) {
            Log.e("iCallBack", "onMsg");
        }

        @Override
        public void onUserAttrResult(String s, String s1, String s2) {
            Log.e("iCallBack", "onUserAttrResult");
        }

        @Override
        public void onUserAttrAllResult(String s, String s1) {
            Log.e("iCallBack", "onUserAttrAllResult");
        }

        @Override
        public void onError(final String msg, final int errorCode, final String msg1) {
            runOnUI(new Runnable() {
                @Override
                public void run() {
//                    Toast.makeText(BaojianApplication.getInstance(), "onError:msg:" + msg + " errorCode:" + errorCode + " msg1:" + msg1, Toast.LENGTH_LONG).show();
                }
            });
            switch (errorCode){
                case ECODE_LOGIN_E_ALREADY_LOGIN:
                    runOnUI(new Runnable() {
                        @Override
                        public void run() {
                            AppBus.getInstance().post(Event.AGORA_LOGIN_SUCCESS);
                        }
                    });
                    break;
            }
            Log.e("iCallBack", "onError msg:" + msg + " errorCode:" + errorCode + " msg1:" + msg1);
        }

        @Override
        public void onQueryUserStatusResult(String s, String s1) {

        }

        @Override
        public void onDbg(String s, String s1) {
            Log.e("iCallBack", "onDbg");
        }

        @Override
        public void onBCCall_result(String s, String s1, String s2) {

        }
    };

    private void runOnUI(Runnable runnable){
        ((Activity)context).runOnUiThread(runnable);
    }
}
